/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pinnwand;

import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.ScrollPane;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;

/**
 *
 * @author Chris
 */
public class Pinnwand extends javax.swing.JFrame {

    //Eigene Attribute
    private JTextArea[] save = new JTextArea[10];
    private int check = 0;
    private File daten = new File(System.getProperty("user.dir")+"/save.jspw");
    private ImageIcon notiz = new ImageIcon(ClassLoader.getSystemResource("pinnwand/notiz.png"));
    private TrayIcon tray_icon = new TrayIcon(notiz.getImage(),"Pinnwand");
    private JPopupMenu  popmenu = new JPopupMenu();
    private JMenuItem popopen = new JMenuItem("Öffnen");
    private JMenuItem popclose = new JMenuItem("Schließen");
    /**
     * Creates new form Pinnwand
     */
    public Pinnwand() {
        initComponents();
        popmenu.setSize(100,50);
        popmenu.add(popopen);
        popmenu.add(popclose);
        popopen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt){
               open(); 
            }
        });
        popclose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt){
                System.exit(0);
            }
        });
        tray_icon.setImageAutoSize(true);
        this.setIconImage(notiz.getImage());
        tray_icon.addMouseListener(new java.awt.event.MouseAdapter(){
            public void mouseReleased(java.awt.event.MouseEvent mevt){
                pop_open(mevt.getXOnScreen(),mevt.getYOnScreen());
            }
        });
        try{
            SystemTray.getSystemTray().add(tray_icon);
        }catch(Exception e){
            System.out.println(e.toString());
            Fehler.setText(e.toString());
            Error.setTitle("Fehler beim Erstellen des Trays");
            Error.setVisible(true);
        }
        if(!daten.exists()){
            speichern();
        }
        daten.setReadable(true, false);
        daten.setWritable(true, false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        Create = new javax.swing.JDialog();
        jLabel2 = new javax.swing.JLabel();
        pin_name = new javax.swing.JTextField();
        pin_create = new javax.swing.JButton();
        Error = new javax.swing.JDialog();
        Fehler = new javax.swing.JLabel();
        error_okay = new javax.swing.JButton();
        pin_tabs = new javax.swing.JTabbedPane();
        pin_new = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        pin_save = new javax.swing.JButton();
        pin_del = new javax.swing.JButton();
        resize = new javax.swing.JButton();

        Create.setTitle("Neue Wand");
        Create.setAlwaysOnTop(true);
        Create.setMinimumSize(new java.awt.Dimension(300, 120));
        Create.setResizable(false);

        jLabel2.setText("Bitte Namen der neuen Wand eingeben:");

        pin_create.setText("Erstellen");
        pin_create.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pin_createActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout CreateLayout = new javax.swing.GroupLayout(Create.getContentPane());
        Create.getContentPane().setLayout(CreateLayout);
        CreateLayout.setHorizontalGroup(
            CreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CreateLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(CreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(CreateLayout.createSequentialGroup()
                        .addGroup(CreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(pin_create, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(pin_name, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 90, Short.MAX_VALUE)))
                .addContainerGap())
        );
        CreateLayout.setVerticalGroup(
            CreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CreateLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pin_name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pin_create)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        Error.setTitle("Fehler");
        Error.setAlwaysOnTop(true);
        Error.setMinimumSize(new java.awt.Dimension(280, 100));

        Fehler.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        Fehler.setText("Fehlertext");

        error_okay.setText("Okay");
        error_okay.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        error_okay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                error_okayActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ErrorLayout = new javax.swing.GroupLayout(Error.getContentPane());
        Error.getContentPane().setLayout(ErrorLayout);
        ErrorLayout.setHorizontalGroup(
            ErrorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ErrorLayout.createSequentialGroup()
                .addGroup(ErrorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ErrorLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(Fehler, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(ErrorLayout.createSequentialGroup()
                        .addGap(83, 83, 83)
                        .addComponent(error_okay, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 76, Short.MAX_VALUE)))
                .addContainerGap())
        );
        ErrorLayout.setVerticalGroup(
            ErrorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ErrorLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Fehler)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(error_okay)
                .addContainerGap())
        );

        setTitle("Pinnwand - DarkSource");
        setBounds(new java.awt.Rectangle(0, 0, 620, 620));
        setLocationByPlatform(true);
        setMaximumSize(new java.awt.Dimension(630, 300));
        setMinimumSize(new java.awt.Dimension(620, 300));
        setPreferredSize(new java.awt.Dimension(620, 300));
        setResizable(false);

        pin_tabs.setToolTipText("");
        pin_tabs.setAutoscrolls(true);
        pin_tabs.setMaximumSize(new java.awt.Dimension(580, 600));
        pin_tabs.setMinimumSize(new java.awt.Dimension(580, 0));
        pin_tabs.setPreferredSize(new java.awt.Dimension(580, 300));

        pin_new.setText("Neu");
        pin_new.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pin_newActionPerformed(evt);
            }
        });

        jLabel1.setForeground(new java.awt.Color(0, 0, 204));
        jLabel1.setText("© Darkor | darksource.de");
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel1MouseClicked(evt);
            }
        });

        pin_save.setText("Speichern");
        pin_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pin_saveActionPerformed(evt);
            }
        });

        pin_del.setText("Auswahl löschen");
        pin_del.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pin_delActionPerformed(evt);
            }
        });

        resize.setText("Größe ändern");
        resize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resizeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(pin_new, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pin_save)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pin_del)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(resize, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(51, 51, 51)
                        .addComponent(jLabel1))
                    .addComponent(pin_tabs, javax.swing.GroupLayout.PREFERRED_SIZE, 580, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(pin_tabs, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pin_new)
                    .addComponent(pin_save)
                    .addComponent(pin_del)
                    .addComponent(jLabel1)
                    .addComponent(resize))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void open(){
        this.setVisible(true);
        popmenu.setVisible(false);
    }
    
    private void pop_open(int x, int y){
        popmenu.setLocation(x,y);
        popmenu.setVisible(true);
    }
    
    /*
     * Die Methode öffnet die Erstellungsdialog für einen neuen Pinnwandeintrag
     */
    private void pin_newActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pin_newActionPerformed
        Create.setVisible(true);
    }//GEN-LAST:event_pin_newActionPerformed

    /*
     * Die Methode erstellt einen neuen Pinnwandeintrag
     * Es wir eine TextArea erstell, die Wortumbruch hat und veränderbar ist und im Feld gespeichert
     * Anschließend wird die Area auf ein ScrollPane gesetzt
     * Anschließend wird das ScrollPane auf die Pinnwand gesetzt und erhält den eingegebenen Namen
     * Der Erstellungsdialog wird geschlossen
     */
    private void pin_createActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pin_createActionPerformed
        JTextArea text = new JTextArea();
        text.setWrapStyleWord(true);
        text.setEditable(true);
        save[check]=text;
        check++;
        ScrollPane net = new ScrollPane();
        net.add(pin_name.getText()+"_text", text);
        pin_tabs.add(pin_name.getText(), net);
        pin_tabs.setLayout(new GridLayout(1,1));
        Create.setVisible(false);
    }//GEN-LAST:event_pin_createActionPerformed

    /*
     * Die Methode ruft die speichern Methode auf
     */
    private void pin_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pin_saveActionPerformed
         speichern();
    }//GEN-LAST:event_pin_saveActionPerformed

    /*
     * Die Methode schließt die Fehlermeldung
     */
    private void error_okayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_error_okayActionPerformed
        Error.setVisible(false);
    }//GEN-LAST:event_error_okayActionPerformed

    /*
     * Die Methode ruft die loeschen Methode auf
     */
    private void pin_delActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pin_delActionPerformed
        loeschen();
    }//GEN-LAST:event_pin_delActionPerformed

    private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
        try{
            Desktop.getDesktop().browse(new URI("http://www.darksource.de/"));
        }catch(URISyntaxException | IOException e){
            Fehler.setText(e.toString());
            Error.setTitle("Fehler beim Laden");
            Error.setVisible(true);
        }
    }//GEN-LAST:event_jLabel1MouseClicked

    private void resizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resizeActionPerformed
        if(this.isResizable()){
            resize.setText("Größe ändern");
            this.setResizable(false);
            if(this.getWidth()>615){
                this.setSize(615,this.getHeight());
            }
        }else{
            resize.setText("Größe fixieren");
            this.setResizable(true);
        }
    }//GEN-LAST:event_resizeActionPerformed

    /*
     * Die Methode lädt die Pinnwandeinträge aus der save.jspw Datei
     * Die Position auf dem Bildschirm wird ausgelesen und gesetzt
     * Die Größe des Fenster wird ausgelesen und gesetzt
     * Die Anzahl der Einträge wird ausgelesen
     * Anschließend wird für jeden Eintrag der Name ausgelesen,
     * Ein TextArea und ScrollPane erstellt,
     * Beides unter dem Namen auf die Pinnwand gesetzt
     * Der Jeweils abgespeicherte Text wird nun in die TextArea geladen
     * 
     * Fehlermeldungen werden dem Benutzer direkt mitgeteilt
     */
    private void laden(){
        try{
            BufferedReader load = new BufferedReader(new FileReader(daten));
            if(load.readLine().equalsIgnoreCase("--Infos--")){
                this.setLocation(Integer.parseInt(load.readLine()), Integer.parseInt(load.readLine()));
                this.setSize(Integer.parseInt(load.readLine()), Integer.parseInt(load.readLine()));
            }
            if(load.readLine().equalsIgnoreCase("--Wande--")){
                    check = Integer.parseInt(load.readLine());
                    for(int i = 0;i < check;i++){
                        String e = load.readLine();
                        ScrollPane dev = new ScrollPane();
                        JTextArea text = new JTextArea();
                        text.setWrapStyleWord(true);
                        text.setEditable(true);
                        save[i]=text;
                        dev.add(e+"_text", text);
                        pin_tabs.add(e, dev);
                        String h = load.readLine();
                        if(h.equalsIgnoreCase("--Beginn-"+i+"--")){
                            h = load.readLine();
                            String set ="";
                            while(!(h.equalsIgnoreCase("--Ende-"+i+"--"))){
                                set = set+h+"\n";
                                h = load.readLine();
                            }
                            save[i].setText(set);
                        }
                } 
            }
        }catch(IOException | NumberFormatException e){
            Fehler.setText(e.toString());
            Error.setTitle("Fehler beim Laden");
            Error.setVisible(true);
        }
    }
    
    /*
     * Die Methode speichert die Pinnwandeinträge in die save.jspw Datei
     * Die Kommentierungen werden in der Form --Kommentar-- abgespeichert
     * Die aktuelle Position auf dem Bildschrim wird abgespeichert
     * Die aktuelle Größe des Fensters wird abgespeichert
     * Die Anzahl der Einträge wird abgespeichert
     * Der Titel der Einträge und deren Text werden nacheinander abgespeichert
     * 
     * Fehlermeldungen werden dem Benutzer direkt mitgeteilt
     */
    private void speichern(){
        try (FileOutputStream Saver = new FileOutputStream((daten))) {
                Saver.write("--Infos--\n".getBytes());
                Saver.write((this.getX()+"\n").getBytes());
                Saver.write((this.getY()+"\n").getBytes());
                Saver.write((this.getWidth()+"\n").getBytes());
                Saver.write((this.getHeight()+"\n").getBytes());
                Saver.write("--Wande--\n".getBytes());
                Saver.write((check+"\n").getBytes());
                for(int i = 0;i<check;i++){
                    Saver.write((pin_tabs.getTitleAt(i) +"\n").getBytes());
                    Saver.write(("--Beginn-"+i+"--\n").getBytes());
                    int len = save[i].getText().length();
                    if(save[i].getText().endsWith("\n")){
                        Saver.write((save[i].getText()).getBytes());
                    }else{
                        Saver.write((save[i].getText()+"\n").getBytes());
                    }
                    Saver.write(("--Ende-"+i+"--\n").getBytes());
                }
                Saver.flush();
         }catch(Exception e){
            Fehler.setText(e.toString());
            Error.setTitle("Fehler beim Speichern");
            Error.setVisible(true);
         }
    }
    
    /*
     * Die Methode löscht den aktuellen Eintrag
     * Der aktuell ausgewählte Eintrag wird von der Pinnwand entfernt
     * Anschließend werden alle Texte um eine Stelle nach vorne geschoben
     */
    private void loeschen(){
        int del = pin_tabs.getSelectedIndex();
        pin_tabs.remove(del);
        check--;
        for(int i = del;i<=check;i++){
            save[i].setText(save[i+1].getText());
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Pinnwand.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Pinnwand fu = new Pinnwand();
                fu.setVisible(true);
                fu.laden();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JDialog Create;
    private javax.swing.JDialog Error;
    private javax.swing.JLabel Fehler;
    private javax.swing.JButton error_okay;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton pin_create;
    private javax.swing.JButton pin_del;
    private javax.swing.JTextField pin_name;
    private javax.swing.JButton pin_new;
    private javax.swing.JButton pin_save;
    private javax.swing.JTabbedPane pin_tabs;
    private javax.swing.JButton resize;
    // End of variables declaration//GEN-END:variables
}
